package controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Map;

import view.interfaces.Observer;
import view.normalview.DrawPanel;
import view.normalview.MainWindow;


import Factory.ReaderFactory;
import Factory.UmlFactory;
import Model.diagram.ClassDiagram;
import Model.diagram.UsecasDiagram;
import Model.interfaces.Iassociation;
import Model.interfaces.Idiagrame;

public class Filecontroller implements Observer{

	private MainWindow main;
	File pictureresult;
	File gen;
File buffer;
private int fileresulttracker=0;
DrawPanel panel= new DrawPanel();
private UmlFactory umlfactory=new UmlFactory();
private Idiagrame diagram;
private ReaderFactory readerFactory=new ReaderFactory();
public Filecontroller(MainWindow w){
	this.main=w;
	this.readerFactory=new ReaderFactory();
	
}

public void open(File file) {
	this.buffer=file;
	 gen=createnewFile(file);
	this.diagram=readerFactory.create(file);
	umlfactory.create(diagram);
	panel.add(this);
	
	if(diagram instanceof UsecasDiagram){
		panel.setUpper(umlfactory.convert(gen));
		panel.setupperlist(diagram.listClassen());
		
	}
	if(diagram instanceof ClassDiagram){
		panel.setLower(umlfactory.convert(gen));
		panel.setlowerlist(diagram.listClassen());
	}
	
	main.getFrame().add(panel);
	main.getFrame().setVisible(true);
}


public File createnewFile(File f){
	int last =f.getName().lastIndexOf(".");
	String chek=f.getName().substring(0, last)+".png";
	File kaboom=new File(f.getParent()+File.separator+chek);
	try {
		FileOutputStream png =new FileOutputStream(new File(f.getParent()+File.separator+chek));
		
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return kaboom;
	
}






public Idiagrame getDiagram() {
	return diagram;
}



public void setDiagram(Idiagrame diagram) {
	this.diagram = diagram;
}



public UmlFactory getUmlfactory() {
	return umlfactory;
}



public void setUmlfactory(UmlFactory umlfactory) {
	this.umlfactory = umlfactory;
}

@Override
public void update(Idiagrame dia) {
	umlfactory.create(dia);
	fileresulttracker++;
	if(pictureresult!=null){
		pictureresult.delete();
	}
		
	
	 
	pictureresult= new File(gen.getParentFile()+File.separator+"result"+fileresulttracker+".png");
	panel.setResult(umlfactory.convert(pictureresult));
	
}
}
